package com.niiwoo.civet.mobile.controller.kaola;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.dto.request.kaola.KaoLaDebtResultNotifyRequestDTO;
import com.niiwoo.civet.trade.dto.request.kaola.KaoLaSignNotifyUrlDTO;
import com.niiwoo.civet.trade.dto.response.kaola.KaoLaBaseResponseDTO;
import com.niiwoo.civet.trade.dto.response.kaola.KaoLaCreditAssignmentResponseDTO;
import com.niiwoo.civet.trade.service.koala.KaoLaLiCaiContractDubboService;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;

/**
 * 考拉理财合同签署controller
 *
 * @author liming
 * @date 2017-12-29 11:08
 */
@Slf4j
@RestController
@Api(tags = "考拉理财合同签署(魏黎明)")
public class KaoLaLiCaiContractController {

    @Reference(version = "1.0.0")
    private KaoLaLiCaiContractDubboService kaoLaLiCaiContractDubboService;


    /**
     * @description 考拉待签合同消息通知(法大大将考拉理财发起的签署协议同步给你我金融)
     * @param request
     * @param response
     */
    @PostMapping(value ="/fadada/kaola_sign_notify")
    @ApiOperation(value = "考拉待签合同通知",notes = "法大大调用")
    @AuthIgnore
    public void kaolaSignNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            log.info("考拉待签合同消息通知,请求参数={}",getParam4HttpRequest(request));
            KaoLaSignNotifyUrlDTO kaoLaSignNotifyUrlDTO = trans2KaolaSignNotifyUrlDTO(request);
            log.info("考拉待签合同消息通知,合同ID={},KaolaSignNotifyUrlDTO={}",kaoLaSignNotifyUrlDTO.getContract_id(),kaoLaSignNotifyUrlDTO);
            if(!checkKaolaSignNotifyUrlParam(kaoLaSignNotifyUrlDTO)){
                response.getWriter().write("failed");
                log.info("考拉待签合同消息通知,返回结果={}",response);
                return;
            }
            KaoLaCreditAssignmentResponseDTO responseDTO = kaoLaLiCaiContractDubboService.kaolaSignNotify(kaoLaSignNotifyUrlDTO);

            if(responseDTO.isSuccess()){
                log.info("考拉待签合同消息通知,合同ID={},请求接收成功.",kaoLaSignNotifyUrlDTO.getContract_id());
                response.getWriter().write("success");
            }else{
                log.info("考拉待签合同消息通知,合同ID={},请求接收失败.",kaoLaSignNotifyUrlDTO.getContract_id());
                response.getWriter().write("failed");
            }
        } catch (Exception e) {
            log.error("考拉待签合同消息通知,发生系统异常,原因如下:{}",e);
            try {
                response.getWriter().write("failed");
            } catch (IOException e1) {
                log.error("考拉待签合同消息通知,发生系统异常,原因如下:{}",e);
            }
        }
        log.info("考拉待签合同消息通知,返回结果={}",response.getWriter().toString());
    }

    /**
     * @description 考拉待签合同消息通知请求参数处理
     * @param request
     * @return
     */
    private String getParam4HttpRequest(HttpServletRequest request){
        StringBuffer stringBuffer=new StringBuffer("{");
        Enumeration enu=request.getParameterNames();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            stringBuffer.append("\""+paraName+"\""+":\""+request.getParameter(paraName)).append("\",");
        }
        stringBuffer.append("}");

        return stringBuffer.toString();
    }

    /**
     * 转换考拉待签合同消息通知参数
     * @param request
     * @return
     */
    private KaoLaSignNotifyUrlDTO trans2KaolaSignNotifyUrlDTO(HttpServletRequest request){
        String send_app_id = request.getParameter("send_app_id");
        String contract_id = request.getParameter("contract_id");
        String customer_ids = request.getParameter("customer_ids");
        String push_transaction_id = request.getParameter("push_transaction_id");
        String ex_info = request.getParameter("ex_info");
        String timestamp = request.getParameter("timestamp");
        String msg_digest = request.getParameter("msg_digest");

        KaoLaSignNotifyUrlDTO kaolaSignNotifyUrlDTO=new KaoLaSignNotifyUrlDTO();
        kaolaSignNotifyUrlDTO.setSend_app_id(send_app_id);
        kaolaSignNotifyUrlDTO.setContract_id(contract_id);
        kaolaSignNotifyUrlDTO.setCustomer_ids(customer_ids);
        kaolaSignNotifyUrlDTO.setPush_transaction_id(push_transaction_id);
        kaolaSignNotifyUrlDTO.setEx_info(ex_info);
        kaolaSignNotifyUrlDTO.setTimestamp(timestamp);
        kaolaSignNotifyUrlDTO.setMsg_digest(msg_digest);

        return kaolaSignNotifyUrlDTO;
    }

    /**
     * 检查考拉待签合同消息通知参数
     * @param kaolaSignNotifyUrlDTO
     * @return
     */
    private boolean checkKaolaSignNotifyUrlParam(KaoLaSignNotifyUrlDTO kaolaSignNotifyUrlDTO){
        if(kaolaSignNotifyUrlDTO==null){
            log.error("考拉待签合同消息通知,发生异常,原因是KaolaSignNotifyUrlDTO为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaolaSignNotifyUrlDTO.getSend_app_id())){
            log.error("考拉待签合同消息通知,发生异常,原因是发起方APP_ID(字段:send_app_id)为空.");
            return false;
        }

        if(StringUtils.isEmpty(kaolaSignNotifyUrlDTO.getContract_id())){
            log.error("考拉待签合同消息通知,发生异常,原因是合同编号(字段:contract_id)为空.");
            return false;
        }

        if(StringUtils.isEmpty(kaolaSignNotifyUrlDTO.getCustomer_ids())){
            log.error("考拉待签合同消息通知,发生异常,原因是待签署客户ID集合(字段:customer_ids)为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaolaSignNotifyUrlDTO.getPush_transaction_id())){
            log.error("考拉待签合同消息通知,发生异常,原因是推送交易号(字段:push_transaction_id)为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaolaSignNotifyUrlDTO.getTimestamp())){
            log.error("考拉待签合同消息通知,发生异常,原因是请求时间(字段:timestamp)为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaolaSignNotifyUrlDTO.getMsg_digest())){
            log.error("考拉待签合同消息通知,发生异常,原因是摘要(字段:msg_digest)为空.");
            return false;
        }

        return true;
    }



    /**
     * @description 考拉债权转让协议签署结果异步通知
     * @param request
     * @param response
     */

    @PostMapping(value ="/fadada/kaola_debt_result_notify")
    @AuthIgnore
    @ApiOperation(value = "考拉债权转让协议签署结果异步通知",notes = "法大大调用")
    public void kaolaDebtResultNotifyUrl(HttpServletRequest request,HttpServletResponse response){
        try {
            log.info("考拉法大大债权转让协议签署结果异步通知,请求参数={}",getParam4HttpRequest(request));
            KaoLaDebtResultNotifyRequestDTO requestDTO = trans2KaoLaDebtResultNotifyRequestDTO(request);
            log.info("考拉法大大债权转让协议签署结果异步通知,kaolaDebtResultNotifyDTO={}",requestDTO);
            if(!checkKaolaDebtResultNotifyParam(requestDTO)){
                return;
            }
            KaoLaBaseResponseDTO responseDTO = kaoLaLiCaiContractDubboService.kaolaDebtResultNotify(requestDTO);
            log.info("考拉法大大债权转让协议签署结果异步通知,处理结果={}",responseDTO);
        } catch (Exception e) {
            log.error("考拉待签合同消息通知,发生系统异常,HttpServletRequest={},原因如下:{}",request,e);
        }
    }

    private KaoLaDebtResultNotifyRequestDTO trans2KaoLaDebtResultNotifyRequestDTO(HttpServletRequest request) {
            String transaction_id = request.getParameter("transaction_id");
            String contract_id = request.getParameter("contract_id");
            String result_code = request.getParameter("result_code");
            String result_desc = request.getParameter("result_desc");
            String download_url = request.getParameter("download_url");
            String viewpdf_url = request.getParameter("viewpdf_url");
            String timestamp = request.getParameter("timestamp");
            String msg_digest = request.getParameter("msg_digest");

            KaoLaDebtResultNotifyRequestDTO kaoLaDebtResultNotifyRequestDTO = new KaoLaDebtResultNotifyRequestDTO();
            kaoLaDebtResultNotifyRequestDTO.setTransaction_id(transaction_id);
            kaoLaDebtResultNotifyRequestDTO.setContract_id(contract_id);
            kaoLaDebtResultNotifyRequestDTO.setResult_code(result_code);
            kaoLaDebtResultNotifyRequestDTO.setResult_desc(result_desc);
            kaoLaDebtResultNotifyRequestDTO.setDownload_url(download_url);
            kaoLaDebtResultNotifyRequestDTO.setViewpdf_url(viewpdf_url);
            kaoLaDebtResultNotifyRequestDTO.setTimestamp(timestamp);
            kaoLaDebtResultNotifyRequestDTO.setMsg_digest(msg_digest);
            return kaoLaDebtResultNotifyRequestDTO;
    }

    /**
     * 检查考拉债权转让协议签署结果异步通知参数
     * @param kaoLaDebtResultNotifyRequestDTO
     * @return
     */
    private boolean checkKaolaDebtResultNotifyParam(KaoLaDebtResultNotifyRequestDTO kaoLaDebtResultNotifyRequestDTO){
        if(Objects.isNull(kaoLaDebtResultNotifyRequestDTO)){
            log.error("考拉法大大债权转让协议签署结果异步通知,发生异常,原因是KaoLaDebtResultNotifyRequestDTO为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaoLaDebtResultNotifyRequestDTO.getTransaction_id())){
            log.error("考拉法大大债权转让协议签署结果异步通知,发生异常,原因是交易号(字段:transaction_id)为空.");
            return false;
        }

        if(StringUtils.isEmpty(kaoLaDebtResultNotifyRequestDTO.getContract_id())){
            log.error("考拉法大大债权转让协议签署结果异步通知,发生异常,原因是合同编号(字段:contract_id)为空.");
            return false;
        }

        if(StringUtils.isEmpty(kaoLaDebtResultNotifyRequestDTO.getResult_code())){
            log.error("考拉法大大债权转让协议签署结果异步通知,发生异常,原因是签章结果代码(字段:result_code)为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaoLaDebtResultNotifyRequestDTO.getResult_desc())){
            log.error("考拉法大大债权转让协议签署结果异步通知,发生异常,原因是推送交易号(字段:result_desc)为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaoLaDebtResultNotifyRequestDTO.getTimestamp())){
            log.error("考拉法大大债权转让协议签署结果异步通知,发生异常,原因是请求时间(字段:timestamp)为空.");
            return false;
        }
        if(StringUtils.isEmpty(kaoLaDebtResultNotifyRequestDTO.getMsg_digest())){
            log.error("考拉法大大债权转让协议签署结果异步通知,发生异常,原因是摘要(字段:msg_digest)为空.");
            return false;
        }

        return true;
    }
}
